<template>
  <div id="deptManageDiv">
    <Breadcrumb content="科室管理" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">科室信息</div>
              <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findDeptList" @keyup="keyupEnter" @search-click="handleSearch(searchForm.searchValue)"></vxe-input>
              <el-select v-model="searchForm.orgId" placeholder="请选择" ref="selectOrgRef" filterable style="width: 130px">
                <el-option hidden :value="searchForm.orgId ? searchForm.orgId : ''" :label="searchForm.orgName"></el-option>
                <el-tree filterable :data="orgList" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" @node-click="handleOrgNodeClick" highlight-current ref="orgTreeRef" node-key="id" class="tools-tree"></el-tree>
              </el-select>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findDeptList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addDept(searchForm.orgId, '', '')"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveDept"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showDataLoading" @click="pullDept"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBox" ref="eewerrw">
            <vxe-table ref="deptTable" border="inner" height="auto" class="mytable-scrollbar" :loading="showLoading" :data="departList" :expand-config="{ expandAll: true, reserve: true }" @current-change="deptRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" :tree-config="{
            expandAll: true,
            transform: true,
            rowField: 'id',
            parentField: 'parentId'
          }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <!-- tree-node 只对 tree-config 配置时有效，指定为树节点 -->
              <!-- v-if="row.code.toLowerCase() !== 'all'" -->
              <vxe-column field="code" title="编码" width="140" tree-node :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="name" title="名称" width="120" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.name" @change="autoInputCode(row)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="inputCode" title="助记符" width="120" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.inputCode"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="contactTel" title="联系电话" width="120" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.contactTel"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="address" title="地址" min-width="110" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.address"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="whonetCode" title="whonet编码" min-width="110" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.whonetCode"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="whonetName" title="whonet名称" min-width="110" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.whonetName"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <!-- v-if="row.code.toLowerCase() !== 'all'" -->
                  <div>
                    <el-tooltip class="item" effect="dark" content="新建子分组" placement="right">
                      <vxe-button type="text" status="primary" icon="vxe-icon-square-plus" circle @click.native="addDept(searchForm.orgId, row.id, row)"></vxe-button>
                    </el-tooltip>
                    <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteDept(row)"></vxe-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">授权用户</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="qloading" @click="findUserDepartmentList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" @click="addUserDepartDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="qcItemTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="userDepartmentList" :loading="qloading" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30" align="center"></vxe-column>
              <vxe-column field="username" title="用户名" width="120px">
                <template #edit="{ row }">
                  <vxe-input v-model="row.username" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="realname" title="名字" width="100px">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.realname" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="tel" title="电话" width="120px">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.tel" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="email" title="邮箱" min-width="130px">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.email" type="text"></vxe-input>
                </template>
              </vxe-column>

            </vxe-table>
          </div>
          <el-dialog title="用户" :show-close="false" v-model="showDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showDialog">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-input style="width: 130px" v-model="searchUserForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findSysUserList2" @keyup="keyupUserEnter" @search-click="findSysUserList2()"></vxe-input>
                <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findSysUserList2"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="tableBody" style="height: 600px">
              <vxe-table :data="sysUserList" :loading="lloading" ref="labItemTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>
                <vxe-column title="序号" width="80">
                  <template #default="{ row, rowIndex, column }">
                    <span>{{ rowIndex + 1 }}</span>
                  </template>
                </vxe-column>
                <vxe-column type="checkbox" width="30px"></vxe-column>
                <vxe-column field="username" title="用户名" width="120px">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.username" type="text"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column field="realname" title="名字" width="100px">
                  <template #edit="{ row, rowIndex, column }">
                    <vxe-input v-model="row.realname" type="text"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column field="tel" title="电话" width="120px">
                  <template #edit="{ row, rowIndex, column }">
                    <vxe-input v-model="row.tel" type="text"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column field="email" title="邮箱" min-width="130px">
                  <template #edit="{ row, rowIndex, column }">
                    <vxe-input v-model="row.email" type="text"></vxe-input>
                  </template>
                </vxe-column>
              </vxe-table>

              <div class="dialog-footer flex right justify-end">
                <el-button type="primary" @click="saveBacthQcItem('qcItemTableRef')">确定</el-button>
                <el-button @click="closeDialog('qcItemTableRef')">取消</el-button>
              </div>
            </div>
          </el-dialog>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../stores/store';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式

// 全局变量定义区 ==========
let store = AppStore();

let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态
let showDataLoading = ref(false);

let searchForm = reactive({
  searchValue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
});

let deptTable = ref(null); //部门表格ref
let departList: any = reactive([]); //部门列表数据
let orgList: any = reactive([]); //所有的组织机构
let userDepartmentList: any = reactive([]); //右侧质控项目表格数据
let qloading = ref(false); //右侧质控表格加载+刷新
let lloading = ref(false); //右侧质控表格加载+刷新
let sysUserList: any = reactive([]);
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findOrgTree();
  findDeptList();
});

function findOrgTree() {
  orgList.length = 0;

  const url = '/api/sys/findOrgTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        orgList.push(...res.data.orgTree);
        setCurOrgTreeNode(searchForm.orgId);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取机构失败', VxeNotifyType.error);
    });
}

// 光标定位在指定字典分类上
function setCurOrgTreeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

function handleOrgNodeClick(data: any) {
  searchForm.orgId = data.id;
  searchForm.orgName = data.name;
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
  findDeptList();
}

// 点击部门当前行触发的事件
function deptRowClick({ row }: any) {
  sltDept = row;

  (proxy.$refs.deptTable as any).setCurrentRow(row);
  findUserDepartmentList();
}
let searchUserForm = reactive({
  searchValue: ''
});
// 回车查询
function keyupUserEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findSysUserList2();
  }
}

function findSysUserList2() {
  lloading.value = true;
  sysUserList.length = 0; //放入数据前清空数据
  const url = '/api/user/getUserInfoList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { keywords: searchUserForm.searchValue }
    })
    .then((res: any) => {
      sysUserList.push(...res.data);
      const itemDictIds = userDepartmentList.map((m) => m.userId);
      const ilist = sysUserList.filter((p: any) => itemDictIds.includes(p.id));
      const $table = proxy.$refs.labItemTableRef;
      $table.setCheckboxRow(ilist, true);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}
// 右侧获取质控项目表格数据
function findUserDepartmentList() {
  if (IsEmpty(sltDept)) {
    VxeMessage('请选择部门', VxeNotifyType.error);
  } else {
    qloading.value = true;
    userDepartmentList.length = 0; //放入数据前清空数据
    const url = '/api/userDepartment/findUserDepartmentList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { pid: sltDept.id }
      })
      .then((res: any) => {
        userDepartmentList.push(...res.data);
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}
let showDialog = ref(false); //添加弹框展示状态

// 添加按钮
function addUserDepartDialog() {
  if (IsEmpty(sltDept)) {
    VxeMessage('请选择科室', VxeNotifyType.error);
  } else {
    findSysUserList();
    showDialog.value = true;
  }
}

// 获取弹框表格数据
function findSysUserList() {
  lloading.value = true;
  sysUserList.length = 0; //放入数据前清空数据
  const url = '/api/user/getUserInfoList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {}
    })
    .then((res: any) => {
      sysUserList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
let sltDept: any = reactive({});

// 获取部门列表
function findDeptList() {
  showLoading.value = true;
  departList.length = 0;
  const $table = deptTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
  }

  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { orgId: searchForm.orgId } })
    .then((res: any) => {
      departList.push(...res.data.deptList);
      if (departList.length > 0) {
        const sltObj = departList[0];

        deptRowClick({ row: sltObj }); //点击当前行获取右侧质控项目表格数据
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取部门异常',VxeNotifyType.error)
    });
}

// 获取children那条数据
function getChildren(obj: any) {
  const children = obj.children;
  return children[0];
}
//搜索部门
function handleSearch(row: any) {
  departList.length = 0;

  const $table = deptTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { keywords: row, orgId: searchForm.orgId } })
    .then((res: any) => {
      departList.push(...res.data.deptList);
      // if(proxy.isChildren){
      // orgRowClick({row: this.orgaList[0]})
      // }
      const $table = deptTable.value;
      // $table.loadData(departList);
    })
    .catch((err: any) => {
      VxeMessage('搜索刷新部门失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}

// 同步数据
function pullDept() {
  showDataLoading.value = true;
  const url = '/api/sys/syncOrgDepartments';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/lisInterface/lisInterfacePost',
    code: 'GET_DEPARTMENT'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      showDataLoading.value = false;
      findDeptList();
    })
    .catch((err: any) => {
      showDataLoading.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}

// 新建一级/子部门
async function addDept(orgids: any, parentids: any, row: any) {
  // clearForm();
  const $table = deptTable.value;
  if ($table) {
    // 假设你已经有了表格的引用，比如通过 ref 属性
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      code: '',
      name: '',
      contactTel: '',
      address: '',
      whonetCode: '',
      whonetName: '',
      orgId: orgids != '' || orgids != null ? orgids : null, //左侧机构传过来的id
      parentId: parentids != '' || parentids != null ? parentids : null, //自己是否有id
      id: ''
    };
    //departList.push(record);
    $table.loadData(departList);
    const { row: newRow } = await $table.insertAt(record);
    // 设置编辑行
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveDept() {
  saveLoading.value = true;
  const $table = deptTable.value;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 修改部门
    updateRecords.forEach((e: any) => {
      const url = '/api/sys/editDepartment';
      const tOrganization = e;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          // findDeptList();
          if (res.status.code === 1) {
            VxeMessage('修改部门成功', VxeNotifyType.success);
          } else {
            VxeMessage('修改部门失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改部门异常', VxeNotifyType.error);
        });
    });

    // 新增部门
    InsertRecords.forEach((ele: any) => {
      const url = '/api/sys/addDepartment';
      const tOrganization = ele;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增部门成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增部门失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增部门异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findDeptList();
      saveLoading.value = false;
    }, 500);
  }
}

// 删除部门
function deleteDept(row: any) {
  const $table = deptTable.value;
  $table.setAllTreeExpand(true);
  proxy
    .$confirm('确定删除此部门？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/deleteDepartment/' + row.id;
      if (row.id) {
        proxy.$http.delete(url).then((res: any) => {
          if (res.status.code != 1) {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          } else {
            VxeMessage('删除部门成功', VxeNotifyType.success);
          }
          findDeptList();
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除部门成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function autoInputCode(row: any) {
  row.inputCode = funBdsJsResult('firstPinYinFun', row.name);
}

// 弹框保存的确定按钮
function saveBacthQcItem() {
  const selectRows = (proxy.$refs.labItemTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addQcItemList = [];
    for (const sltRow of selectRows) {
      const qcitem = userDepartmentList.find((qc: any) => qc.userId == sltRow.id);
      if (IsEmpty(qcitem)) {
        const addQcItem = {
          deptId: sltDept.id,
          deptCode: sltDept.code,
          userId: sltRow.id
        };
        addQcItemList.push(addQcItem);
      }
    }
    if (addQcItemList.length > 0) {
      const data = { sysUserDepartmentList: addQcItemList };
      const url = '/api/userDepartment/batchAddSysUserDepartList';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          findUserDepartmentList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeDialog();
}

function closeDialog() {
  searchUserForm.searchValue = '';
  showDialog.value = false;
}

// 删除按钮
function handleDelete() {
  const sltQcItems = (proxy.$refs.qcItemTableRef as any).getCheckboxRecords();
  if (!(sltQcItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { sysUserDepartmentList: sltQcItems };
        const url = '/api/userDepartment/batchDeleteUserDepartmentList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findUserDepartmentList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = userDepartmentList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.userId);
    return p.userId == row.id;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = userDepartmentList.filter((p: any) => {
    // return p.itemDictId == row.id;
  });
  return obj.length == 0;
}
</script>

<style lang="scss" scoped>
#deptManageDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 39px);
    }
  }
}
</style>
